package com.restphp.java.hashdb.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by sofical on 2020/8/6.
 */
public class MD5Utils {
    final static char[]  HEX = "0123456789abcdef".toCharArray();

    private static final ThreadLocal<MessageDigest> MD5_DIGEST_TL = new ThreadLocal<MessageDigest>() {
        @Override
        protected MessageDigest initialValue() {
            try {
                return MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException("Failed to initialize MD5 digest", e);
            }
        }
    };

    public static String toHexString(byte[] b) {
        if (b == null || b.length == 0) {
            return null;
        }
        StringBuilder sb = new StringBuilder(32);
        for (int i = 0; i < b.length; i++) {
            sb.append(HEX[(b[i] >>> 4) & 0x0F]);
            sb.append(HEX[b[i] & 0x0F]);
        }
        return sb.toString();
    }
    public static byte[] encode(byte[] b) {
        if (b == null) {
            return null;
        }
        MessageDigest md5 = MD5_DIGEST_TL.get();
        md5.update(b);
        return md5.digest();
    }
    public static String encode(String s) {
        if (s == null) {
            return null;
        }
        return toHexString(encode(s.getBytes()));
    }
}
